package com.example.ex2.controller;

import com.example.ex2.common.CommonResponse;
import com.example.ex2.domain.Item;
import com.example.ex2.service.ItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class ItemController {

    @Autowired
    private ItemService itemService;

    @PostMapping("/item")
    public CommonResponse<Item> addItem(@RequestBody Item item){
        System.out.println(item);
        String link = "http://localhost:8080/item";
        if(itemService.addItemByItem(item))
            return CommonResponse.createForSuccess("新增成功", link);
        else
            return CommonResponse.createForError("新增失败",link);
    }

    @DeleteMapping("/item/{id}")
    public CommonResponse<Item> deleteItem(@PathVariable("id") int id){
        String link = "http://localhost:8080/item/" + Integer.toString(id);
        if(itemService.deleteItemById(id))
            return CommonResponse.createForSuccess("删除成功",link);
        else
            return CommonResponse.createForError("删除失败",link);
    }

    @GetMapping("/item")
    public CommonResponse<List<Item>> getAllItems(){
        String link = "http://localhost:8080/item";
        List<Item> itemList = itemService.selectAllItems();
        if(itemList.size() > 0)
            return CommonResponse.createForSuccess("查询成功", itemList, link);
        else
            return CommonResponse.createForError("查询不到相关数据",link);
    }

    @PutMapping("/item")
    public CommonResponse<Item> updateItem(@RequestBody Item item){
        String link = "http://localhost:8080/item";
        if(itemService.updateItemByItem(item))
            return CommonResponse.createForSuccess("更新成功", link);
        else
            return CommonResponse.createForError("更新失败",link);
    }
}
